(function(){
	$.oldAjax=$.ajax
	$.ajax=function(options){
		if(options.dataType=='json' || options.dataType=='png'){
			var waitIndex;
			if($.layer && ((typeof options.waitting=='undefined') || options.waitting)){
				waitIndex=$.layer.load(0, {shade: 0.2});
			}
			
			if(!options.headers){
				options.headers={};
			}
			var tk=$.cookie('tK')||"Authorization";
			var tf=$.cookie("tF");
			var token=options.headers[tk];
			if(!token){
				var th=$.cookie("tH");
				if(tf && th){
					options.headers[tk]=th+" "+tf;
					updateTokenTime(tf, th);
				}
			}else{
				tf=token.substring(token.indexOf(' ')+1);
			}
			var datetime=new Date().getTime();
			options.headers.Datetime=datetime;
			options.headers.Language=$.config.language;
			if(!options.headers.upload){
				options.headers["Content-Type"]="application/json";
				options.headers["Sign"]=dataSign(options, tf);
			}
			options.url=getServletPrefix(options.url)+options.url;
			var event=new AjaxEvent(options.dataType,options.success,options.data?options.error:undefined, waitIndex, options.headers);
			if(options.data){
				delete options.data.errBack;
			}
			options.success=event.success;
		}
		$.oldAjax(options);
	};
	function updateTokenTime(tf, th){
		if(!tf){
			tf=$.cookie("tF");
			th=$.cookie("tH");
		}
		var expire=parseInt($.cookie("tE"));
		$.cookie("tF", tf, expire);
		$.cookie("tH", th, expire);
	}
	function getServletPrefix(url){
		var server, domain, routes;
		for(var i=0, length=$.config.domains.length; i<length; i++){
			domain=$.config.domains[i];
			routes=domain.routes;
			for(var j=0, length2=routes.length; j< length2; j++){
				if(url.startsWith(routes[j])){
					server=domain.server;
					break;
				}
			}
			if(server){
				break;
			}
		}
		if(!server){
			throw new Error("无法确定请求地址")
		}
		return server;
	}
	
	function AjaxEvent(dataType, back_, fail_, waitIndex, headers){
		this.dataType=dataType;
		this.back_=back_;
		this.fail_=fail_;
		this.waitIndex=waitIndex;
		var this_=this;
		this.success=function(data){
			if(this_.waitIndex){
				$.layer.close(this_.waitIndex);
			}
			if(this_.dataType=='json' && !headers.originalData){
				if(data.code && data.code=='0'){
					if(this_.back_){
						this_.back_(data.body);
					}
				}else if(data.code=='10001430'){//尚未登录
					window.location.href='/pages/admin/login.html?msg='+decodeURIComponent(data.message);
				}else{
					if(this_.fail_){
						var result=this_.fail_(data);
						if(result){
							$.layer.msg(data.message);
						}
					}else if($.layer){
						$.layer.msg(data.message);
					}else{
						window.alert(data.message);
					}
				}
			}else if(this_.back_){
				this_.back_(data);
			}
		}
	}
	$.post=function(url, args1, args2, args3, args4){
		var options;
		if(typeof args1=='function'){
			options={
				url:url,
				type:'POST',
				dataType:args2,
				success:args1,
				waitting:args3
			}
		}else{
			options={
				url:url,
				type:'POST',
				dataType:args3,
				data:args1?(typeof args1=='string')?args1:$.toJson(args1):null,
				success:args2,
				waitting:args4
			}
		}
		$.ajax(options);
	};
	$.put=function(url, args1, args2, args3, args4){
		var options;
		if(typeof args1=='function'){
			options={
				url:url,
				type:'PUT',
				dataType:args2,
				data:null,
				success:args1,
				waitting:args3
			}
		}else{
			options={
				url:url,
				type:'PUT',
				dataType:args3,
				data:args1?(typeof args1=='string')?args1:$.toJson(args1):null,
				success:args2,
				waitting:args4
			}
		}
		$.ajax(options);
	};
	$["delete"]=function(url, args1, args2, args3, args4){
		var options;
		if(typeof args1=='function'){
			options={
				url:url,
				type:'DELETE',
				dataType:args2,
				data:null,
				success:args1,
				waitting:args3
			}
		}else{
			options={
				url:url,
				type:'DELETE',
				dataType:args3,
				data:args1?(typeof args1=='string')?args1:$.toJson(args1):null,
				success:args2,
				waitting:args4
			}
		}
		$.ajax(options);
	};
	$.cookie=function(key,value,time){//获取cookie和设置cookie
		if(typeof value=='undefined'){
			var cookies=document.cookie;
			var index=cookies.indexOf(key+"=");
			if(index==-1){
				return false;
			}
			index=index+key.length+1;
			var last=cookies.indexOf(";", index);
			if(last==-1){
				last=cookies.length;
			}
			return $.trim(cookies.substring(index,last));
		}else{
			var date=new Date();
			date.setTime(date.getTime()+time);
			document.cookie=key+"="+value+";expires="+date.toGMTString();
		}
	};
	$.formToData=function(formId, arrayFields){
		formId=typeof formId=='string'?$("#"+formId):formId;
		var json={};
		var formParams=formId.serializeArray();
		var isArray;
		$.each(formParams, function(){
			if(this.value){
				if (json[this.name] != undefined) {
					if (!json[this.name].push) {
						json[this.name] = [json[this.name]];
					}
					json[this.name].push(this.value || '');
				} else {
					isArray=false;
					if(arrayFields){
						for(var j=0, length2=arrayFields.length;j<length2;j++){
							if(arrayFields[j]==this.name){
								isArray=true;
								break;
							}
						}
					}
					if(isArray){
						json[this.name] = [this.value || ''];
					}else{
						json[this.name] = this.value || '';
					}
				}
			}
		});
		return json;
	}
	$.formToJson=function(formId, arrayFields){
		formId=typeof formId=='string'?$("#"+formId):formId;
		var json={};
		var formParams=formId.serializeArray();
		var isArray;
		$.each(formParams, function(){
			if(this.value){
				if (json[this.name] != undefined) {
					if (!json[this.name].push) {
						json[this.name] = [json[this.name]];
					}
					json[this.name].push(this.value || '');
				} else {
					isArray=false;
					if(arrayFields){
						for(var j=0, length2=arrayFields.length;j<length2;j++){
							if(arrayFields[j]==this.name){
								isArray=true;
								break;
							}
						}
					}
					if(isArray){
						json[this.name] = [this.value || ''];
					}else{
						json[this.name] = this.value || '';
					}
				}
			}
		});
		return JSON.stringify(json);
	}
	$.valiForm=function(formId){
		formId=typeof formId=='string'?$("#"+formId):formId;
		var pass=true;
		formId.find(" [required='required']").each(function(){
			if(this.nodeName=='DIV'){
				if(!this.innerHTML){
					$.layer.msg($(this).attr("placeholder")+"不能为空");
					pass=false;
					return false;
				}
			}else{
				if(!this.value){
					$.layer.msg($(this).attr("placeholder")+"不能为空");
					pass=false;
					return false;
				}
			}
		});
		return pass;
	}
	$.width=function(){
		return document.documentElement.clientWidth||document.documentElement.offsetWidth||document.body.clientWidth||document.body.offsetWidth;
	};
	$.height=function(){
		return document.documentElement.clientHeight||document.documentElement.offsetHeight||document.body.clientHeight||document.body.offsetHeight;
	};
	$.loadFormData=function(formId, method, url, data, back){
		$.ajax({
			url:url,
			type:method,
			data:data,
			dataType:'json',
			success:function(data){
				var form=$(formId),field,value,nodeName;
				for(var key in data){
					field=form.find("[name='"+key+"']");
					if(field.exists()){
						if(field.length==1){
							nodeName=field[0].nodeName.toUpperCase();
							if(nodeName=='INPUT' || nodeName=='SELECT' || nodeName=='TEXTAREA'){
								field.val(data[key]||'');
							}else{
								field.html(data[key]||'');
							}
						}else{
							value=data[key]||'';
							field.each(function(){
								if(value==this.value){
									this.checked=true;
								}
							});
						}
					}
				}
				if(back){
					back(data, form);
				}
			}
		});
	}
	$.fn.exists=function(){
		if(this && this.length>0){
			return true;
		}
		return false;
	};
	$.fn.equals=function(node){
		if(this==node || this==node[0] || this[0]==node[0]){
			return true;
		}
		return false;
	};
	$.textHeight=function(text, unitHeight, maxWidth){
		var match=text.match(/\n/g);
		var length=!match?0:match.length;
		var height=((length+1)*unitHeight);
		var array=text.split('\n'),charLength,char;
		for ( var i = 0, length=array.length; i < array.length; i++) {
			charLength=0;
			for ( var j = 0, length2=array[i].length; j < length2; j++) {
				char=array[i].charCodeAt(j);
				if(char>256){
					charLength+=2;
				}else if(char==9){
					charLength+=8;
				}else if(char!=13){
					charLength++;
				}
			}
			height+=parseInt(charLength/maxWidth)*unitHeight;
		}
		return height;
	};
	$.hrefHash=function(value, replace){
		var hash=window.location.hash;
		if(typeof value=='undefined'){
			if(hash){
				var hashArray=hash.substring(1);
				hashArray=hashArray.split('|');
				return hashArray;
			}
			return null;
		}
		if(replace){
			
		}
	};
	$.selectComp=function(options){
		$.selectComp.options=options;
		var select=typeof options.selectShow=='string'?$(options.selectShow):options.selectShow;
		options.selectShow=select;
		options.select=typeof options.select=='string'?$(options.select):options.select;
		var dataList=options.dataList;
		var keyName=options.keyName||"key";
		var valueName=options.valueName||"value";
		var otherAttr=options.otherAttr;
		select.click(function(){
			$.selectComp.index=$.layer.open({
				type: 1,
				title: false,
				area: ["1000px","400px"],
				content: '<div id="selectComp" class="select-comp"></div>'
			});
			var comp=$("#selectComp");
			var html="";
			for(var i=0,length=dataList.length;i<length;i++){
				html+="<span class=\"comp-item\" key=\""+dataList[i][keyName]+"\"";
				if(otherAttr){
					for(var key in otherAttr){
						html+=" "+otherAttr[key]+"=\""+dataList[i][key]+"\"";
					}
				}
				html+=" onclick=\"$.selectComp.selected(this);\">"+dataList[i][valueName]+"</span>";
			}
			comp.html(html);
		});
	};
	$.selectComp.selected=function(option){
		var option=$(option);
		$.selectComp.options.select.val(option.attr("key"));
		$.selectComp.options.selectShow.val(option.html());
		if(typeof $.selectComp.options.selected!='undefined'){
			$.selectComp.options.selected(option, $.selectComp.original);
		}
		$.selectComp.selectedOption=undefined;
		$.layer.close($.selectComp.index);
	};
	$.printParam=function(obj){
		for(var key in obj){
			console.log(key+"="+obj[key]);
		}
	};
	$.toJson=function(data, format){
		return JSON.stringify(data, null, format);
	};
	$.parseHrefParam=function(key){
		var href=window.location.href;
		var index=href.indexOf('#');
		if(index!=-1){
			var param=href.substring(index+1);
			params=param.split('&');
			var paramObj={}, paramItem;
			for(var i=0, length=params.length;i< length;i++){
				paramItem=params[i].split('=');
				paramObj[paramItem[0].trim()]=(paramItem[1]||'').trim();
			}
			if(key){
				return paramObj[key];
			}else{
				return paramObj;
			}
		}
		index=href.indexOf('?');
		if(index!=-1){
			var param=href.substring(index+1);
			params=param.split('&');
			var paramObj={}, paramItem;
			for(var i=0, length=params.length;i< length;i++){
				paramItem=params[i].split('=');
				paramObj[paramItem[0].trim()]=(paramItem[1]||'').trim();
			}
			if(key){
				return paramObj[key];
			}else{
				return paramObj;
			}
		}
		return null;
	};
	$.uuid=function() {
	    var s = [];
	    var hexDigits = "0123456789abcdef";
	    for (var i = 0; i < 36; i++) {
	        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	    }
	    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	    s[8] = s[13] = s[18] = s[23] = "-";
	 
	    var uuid = s.join("");
	    return uuid.replace(/-/g, '').toUpperCase();
    };
    $.dateFormat=function(date, format){
		if(typeof date=='string'){
			format=date;
			date=new Date();
		}
		const year = date.getFullYear().toString().padStart(4, '0').substring(2);
		const fullYear = date.getFullYear().toString().padStart(4, '0');
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		const hour = date.getHours().toString().padStart(2, '0');
		const minute = date.getMinutes().toString().padStart(2, '0');
		const second = date.getSeconds().toString().padStart(2, '0');
		return format.replace(/yyyy/g, fullYear).replace(/yy/g, year).replace(/MM/g, month).replace(/dd/g, day).replace(/HH/g, hour).replace(/mm/g, minute).replace(/ss/g, second);
	};
	$.timeConvert=function(time){
		if(time<0){
			return '0毫秒'
		}else if(time<1000){
			return time+"毫秒";
		}else if(time<60*1000){
			return (time*1.0/1000).toFixed(2)+"秒";
		}else if(time<60*60*1000){
			return (time*1.0/60/1000).toFixed(2)+"分";
		}else if(time<24*60*60*1000){
			return (time*1.0/60/60/1000).toFixed(2)+"小时";
		}else{
			return (time*1.0/24/24/60/1000).toFixed(2)+"天";
		}
	};
    function dataSign(options, token){
		var sourceData=options.url;
		if(options.data){
			if(typeof options.data=='string'){
				sourceData+=options.data;
			}else{
				var index=0;
				for(var key in options.data){
					sourceData+=(index==0?'?':'&')+key+'='+options.data[key];
					index++;
				}
			}
		}
		sourceData+=options.headers.Datetime;
		sourceData+=options.headers.Language;
		if(!token){
			token=getDefaultKey();
		}
		sourceData+=token;
		console.log('sign-data:'+sourceData);
		return md5(sourceData);
	}
	
	function getDefaultKey(){
		var keyArray=[48,51,55,68,56,56,57,54,65,55,55,67,52,53,53,53,57,48,69,70,51,50,68,48,68,67,51,55,65,54,69,69];
		var key='';
		for(var i=0,length=keyArray.length;i<length;i++){
			key+=String.fromCharCode(keyArray[i]);
		}
		console.log(key);
		return key;
	}
})()